﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Manul.Genetics.Character
{
    public class CharacterDirectory : CharacterItem
    {
        public CharacterDirectory()
        {
            IsSuperRoot = false;
        }

        public CharacterDirectory(bool isSuperRoot)
        {
            IsSuperRoot = isSuperRoot;
        }

        public bool IsSuperRoot
        { get; private set; }

        public List<CharacterItem> Characters = new List<CharacterItem>();

        public override NamedItem FindByGuid(string guid)
        {
            NamedItem namedItem = base.FindByGuid(guid);
            if (namedItem != null)
                return namedItem;
            foreach(CharacterItem characterItem in Characters)
                if ((namedItem = characterItem.FindByGuid(guid)) != null)
                    return namedItem;
            return null;
        }

        public override void Swap(int index1, int index2)
        {
            if (IsInList(index1) && IsInList(index2))
            {
                CharacterItem characterItem = Characters[index1];
                Characters.RemoveAt(index1);
                Characters.Insert(index2, characterItem);
            }
        }

        public void Add(CharacterItem item)
        {
            item.Parent = this;
            Characters.Add(item);
        }

        public override bool IsInList(int index)
        {
            return index >= 0 && index < Characters.Count;
        }

        #region ICompilable Members

        public override List<Manul.Genetics.Compiler.CompilationResult> Compile(GenomData genomDataItem)
        {
            List<Manul.Genetics.Compiler.CompilationResult> result = new List<Manul.Genetics.Compiler.CompilationResult>();
            foreach (Character character in this.Characters)
                result.AddRange(character.Compile(genomDataItem));
            return result;
        }

        #endregion
    }
}
